//
//  HJCComposeViewController.swift
//  新浪微博Swift
//
//  Created by 郝俊聪 on 15/5/22.
//  Copyright (c) 2015年 heima. All rights reserved.
//

import UIKit
import SVProgressHUD

let maxTextLength = 10  //文本最大长度
class HJCComposeViewController: UIViewController{
    
    @IBOutlet weak var sendItem: UIBarButtonItem!
    
    @IBOutlet weak var titleNameLbl: UILabel!

    @IBOutlet weak var textView: HJCTextView!
    
    @IBOutlet weak var toolbarBottomConstraint: NSLayoutConstraint!
    
    @IBOutlet weak var containerViewHieghtConstraint: NSLayoutConstraint!
    
    //表情键盘控制器
    lazy var emoticonKeyboardVC : HJCEmoticonKeyboardViewController = {
        weak var weakSelf  = self
        let emoVC = HJCEmoticonKeyboardViewController()
        emoVC.insertEmoticon = {(cell:EmoticonCell) in
            weakSelf!.textView.insertEmoticon(cell)
            weakSelf!.textViewDidChange(weakSelf!.textView)
        }
        return emoVC
        }()
    
    ///图片选择控制器
    var ComposeImageCollectionViewController : HJCComposeImageCollectionViewController?
    
    var placeHolder : UILabel = {
        let placeHolder = UILabel(frame: CGRectMake(6, 8, 0, 0))
        placeHolder.text = "分享新鲜事..."
        placeHolder.textColor = UIColor.lightGrayColor()
        placeHolder.sizeToFit()
        return placeHolder
        }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //布局UI
        setUI()
        //注册通知
        registNotification()
        
    }
    
    func setEmoticonKeyBoard(){
        addChildViewController(emoticonKeyboardVC)
        //先关闭键盘
        //记录文字光标位置
        let selectedRange = textView.selectedRange
        textView.resignFirstResponder()
        //换键盘inputView
        textView.inputView =  (textView.inputView == nil) ?  emoticonKeyboardVC.view : nil
        //打开键盘
        textView.becomeFirstResponder()
        //恢复光标
        textView.selectedRange = selectedRange
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        textView.becomeFirstResponder()
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        textView.resignFirstResponder()
    }

    ///设置初始UI的函数
    func setUI(){
        //设置用户名
         titleNameLbl.text = sharedaccount?.name
        self.automaticallyAdjustsScrollViewInsets = false
        //设置textView的占位视图
        textView.addSubview(placeHolder)
      
        //设置textView的代理
        textView.delegate = self
        
        //设置照片选择控制器
        for vc in childViewControllers{
            if vc is HJCComposeImageCollectionViewController{
                ComposeImageCollectionViewController = vc as? HJCComposeImageCollectionViewController
                break
            }
        }
    }
   
    //注册通知
    func registNotification(){
       NSNotificationCenter.defaultCenter().addObserver(self, selector: "moveToobar:", name: UIKeyboardWillShowNotification, object: nil)
       NSNotificationCenter.defaultCenter().addObserver(self, selector: "moveToobar:", name: UIKeyboardWillHideNotification, object: nil)
    }
    //移除通知
    deinit{
       NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //键盘通知要执行的方法
    func moveToobar(n:NSNotification){
        
//        println(n.userInfo)
        let duration = n.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! CGFloat
        let keyBoardRectValue = n.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue
        let keyBoardRect = keyBoardRectValue.CGRectValue()
        let keyBoardHeigth = keyBoardRect.size.height
        
        var height = CGFloat(0)
        //判断是否是边框变动
        if n.name == UIKeyboardWillShowNotification{
            height = keyBoardHeigth
            UIView.animateWithDuration(Double(duration), animations: { () -> Void in
                self.toolbarBottomConstraint.constant = height
                self.view.layoutIfNeeded()
                }) { (_) -> Void in
                    
            }
        }else{
            self.toolbarBottomConstraint.constant = height
//            self.view.layoutIfNeeded()
        }
    }
    
    
    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        textView.resignFirstResponder()
    }
    
    //MARK: - 操作部分
    ///点击取消按钮
    @IBAction func clickCancelItem(sender: AnyObject) {
        dismissViewControllerAnimated(true, completion: nil)
    }
    ///点击发送微博按钮
    @IBAction func clickSendItem(sender: AnyObject) {
        
        if ComposeImageCollectionViewController?.pictures.count == 0{
            //只有文字时
            let urlStr = "https://api.weibo.com/2/statuses/update.json"
            let parma = ["access_token":sharedaccount?.access_token,"status":textView.fullText()]
            HJCNetWorkTools.uploadText(urlStr, parameters: parma) { (JSON) -> () in
                if JSON == nil{
                   SVProgressHUD.showErrorWithStatus("发送失败")
                }
                self.dismissViewControllerAnimated(true, completion: nil)
            }
        }else{
            //有图片时
            let urlStr = "https://upload.api.weibo.com/2/statuses/upload.json"
            let parma = ["access_token":sharedaccount!.access_token,"status":textView.fullText()]
            //取一个图片（）
            let image = ComposeImageCollectionViewController!.pictures[0]
//            println(image)
            //装成二进制数据
            let data = UIImagePNGRepresentation(image)
            let dataList = ["hmpic":data]
            
            HJCNetWorkTools.uploadTextAndPic(urlStr, fieldName:"pic", dataList: dataList, parameters: parma, finished: { (error) -> () in
                if error != nil{
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
                }
                
                self.dismissViewControllerAnimated(true, completion: nil)
            })
        
        }
        
        
    }
    
   ///点击照片
    @IBAction func clickPictureItem(sender: UIButton) {
        
        containerViewHieghtConstraint.constant = UIScreen.mainScreen().bounds.size.height/3
        self.view.layoutIfNeeded()
        
    }
    
    ///点击表情
    @IBAction func clickEmoticonItem() {
        setEmoticonKeyBoard()
    }
   
}

extension HJCComposeViewController:UITextViewDelegate{
    //textview文字变化处理
    func textViewDidChange(textView: UITextView) {
           let myTextView = textView  as! HJCTextView
           sendItem.enabled = myTextView.hasText()
           placeHolder.hidden = myTextView.hasText()

           //设置字数限制，当超过10文字自动截取
        let str = textView.text as NSString
        if str.length > maxTextLength{
           textView.text = str.substringToIndex(maxTextLength)
        }
    }
    
    
    
}

